﻿//
// GNS_HallScene.cpp
// GameHall
//
// Created by mr.l on 16/1/11.
//
#include "GnsClientFrame.h"
#include "GNS_HallScene.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "GNS_Common.h"
#include "GNS_PlayerMgr.h"
#include "SystemMgr.h"
#include "GNS_ClientHall.h"
#include "GNS_LoginScene.h"

USING_NS_CC;
using namespace cocostudio::timeline;
using namespace ui;

enum{
	GAME_TAG_0 = 0,
	GAME_TAG_1,
	GAME_TAG_2,
	GAME_TAG_3,
	HALL_BACK,
	HALL_QR_TAG ,
	HALL_MANAGE_TAG ,
	HALL_FRIEND_TAG ,
	HALL_SYSTEM_TAG,
	HALL_SIGN_TAG ,
	HALL_LIST_TAG,
	HALL_TICK_TAG,
	HALL_SERVICE,
	HALL_INFO,
	HALL_MSG,
	BTN_RIGHT,
	BTN_LEFTT,
	BTN_DOWN_SUBIMT,   //确定下载
	BTN_DOWN_QX,       //取消下载
};

#define winsize Director::getInstance()->getVisibleSize()



GNS_HallScene::GNS_HallScene()
	:m_isStartGame(false)
{
}

GNS_HallScene::~GNS_HallScene()
{	
}

Scene* GNS_HallScene::createScene()
{
    auto scene = Scene::create();
    auto layer = GNS_SceneMgr::getInstance()->AddSceneLayer(LAYER_HALL);
    scene->addChild(layer);
    return scene;
}

bool GNS_HallScene::init()
{
	AddKeyboard(true);
    if ( !GNS_YJFLayer::init() )
    {
        return false;
    }
    initData();

    return true;
}

#pragma mark - initData
void GNS_HallScene::initData()
{
	m_RootNode = Loadcsb("MainScenes/HallScene.csb");
	m_RootNode->setPosition(Vec2(winsize.width / 2, winsize.height / 2));
	addChild(m_RootNode, 0, 10);

	auto backBtn = static_cast<Button*>(m_RootNode->getChildByName("Button_25"));
	backBtn->setTag(HALL_BACK);
	backBtn->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));

    auto IconButton = static_cast<Button*>(m_RootNode->getChildByName("Button_1"));
    IconButton->setTag(HALL_INFO);
    IconButton->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));
    
    auto QRButton = static_cast<Button*>(m_RootNode->getChildByName("Button_code"));
    QRButton->setTag(HALL_QR_TAG);
    QRButton->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));
    
    auto GameManage = static_cast<Button*>(m_RootNode->getChildByName("Button_mage"));
	GameManage->setTag(HALL_MSG);
    GameManage->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));
    
    auto FriendButton =static_cast<Button*>(m_RootNode->getChildByName("Button_friend"));
    FriendButton->setTag(HALL_FRIEND_TAG);
    FriendButton->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));
    
    auto SystemButton = static_cast<Button*>(m_RootNode->getChildByName("Button_sys"));
    SystemButton->setTag(HALL_SYSTEM_TAG);
    SystemButton->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));
    
    auto SignButton = static_cast<Button*>(m_RootNode->getChildByName("Button_13"));
    SignButton->setTag(HALL_SIGN_TAG);
    SignButton->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));
    
    auto ListButton = static_cast<Button*>(m_RootNode->getChildByName("Button_13_0"));
	ListButton->setTag(HALL_LIST_TAG);
	ListButton->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));
    
    auto TickButton = static_cast<Button*>(m_RootNode->getChildByName("Button_13_2"));
    TickButton->setTag(HALL_TICK_TAG);
    TickButton->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));
	TickButton->setVisible(false);

	SignButton->setPosition(Vec2(TickButton->getPositionX(), TickButton->getPositionY()));
    
    auto ServeButton = static_cast<Button*>(m_RootNode->getChildByName("Button_13_1"));
    ServeButton->setTag(HALL_SERVICE);
    ServeButton->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));

	auto game0 = static_cast<Button*>(m_RootNode->getChildByName("Button_9"));
	//game0->setTag(GAME_TAG_0);
	//game0->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::GameBtnCallBack, this));
	//m_GameBtn[0] = game0;
	//m_GameBtn[0]->setEnabled(false);
	game0->setVisible(false);

	auto game1 = static_cast<Button*>(m_RootNode->getChildByName("Button_10"));
	//game1->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::GameBtnCallBack, this));
	game1->setVisible(false);
	//m_GameBtn[1] = game1;

	auto game2 = static_cast<Button*>(m_RootNode->getChildByName("Button_11"));
	//game2->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::GameBtnCallBack, this));
	game2->setVisible(false);
	//m_GameBtn[2] = game2;
	//m_GameBtn[2]->setEnabled(false);

	auto btnR = static_cast<Button*>(m_RootNode->getChildByName("Button_3"));
	btnR->setTag(BTN_RIGHT);
	btnR->setEnabled(false);
	btnR->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));

	auto btnL = static_cast<Button*>(m_RootNode->getChildByName("Button_2"));
	btnL->setTag(BTN_LEFTT);
	btnL->setEnabled(false);
	btnL->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));

	m_MsgTips = static_cast<Sprite*>(m_RootNode->getChildByName("Sprite_1"));
	m_MsgTips->setVisible(false);

	m_FriendTips = static_cast<Sprite*>(m_RootNode->getChildByName("Sprite_1_0"));
	m_FriendTips->setVisible(false);

	string nameStr = GNS_PlayerMgr::GetInstance()->getMyNickName();
	setNickName(nameStr.c_str());
	setFaceLogo();
	setExperienceGold(GNS_PlayerMgr::GetInstance()->getMyExperienceGold());
	setGameGold(GNS_PlayerMgr::GetInstance()->getMyGameGold());
}

void GNS_HallScene::onEnterTransitionDidFinish()
{
	/*map<int, CMD_SC_HALLGAME_LIST>::iterator itr = GNS_PlayerMgr::GetInstance()->getGameInfoStruct()->begin();
	for (int i=0; itr != GNS_PlayerMgr::GetInstance()->getGameInfoStruct()->end();i++, ++itr)
	{
		  //此处处理游戏按钮是否有效！！
		if (itr->second.nGameId==10)   //暂时这么写着
		{
			m_GameBtn[1]->setTag(itr->first);
		}
		
// 		if (itr->second.bIsForbidRun)
// 		{
// 			m_GameBtn[i]->setUserData((int*)1);
// 			m_GameBtn[i]->setEnabled(true);
// 		}
// 		else
// 		{
// 			m_GameBtn[i]->setUserData(NULL);
// 			m_GameBtn[i]->setEnabled(false);
// 		}
		
	}*/

	// 事件桥梁定时器
	IEventBridge::getInstance()->start();
	this->schedule(schedule_selector(GNS_HallScene::OnEventBridge), 0.1f);
	m_isFinish = false;

	this->schedule(schedule_selector(GNS_HallScene::ReqRankData), 1000 * 60 * 10);
	//ShowSing();   //弹出公告
	this->scheduleOnce(schedule_selector(GNS_HallScene::delayShowSing), 0.01);

	//this->schedule(schedule_selector(GNS_HallScene::showGame), 0.1f);
}


void GNS_HallScene::onExitTransitionDidStart()
{
	m_isFinish = true;
	IEventBridge::getInstance()->stop();
	unschedule(schedule_selector(GNS_HallScene::OnEventBridge));
}

void GNS_HallScene::ShowMsgTips()
{
	if (m_MsgTips == nullptr)
	{
		return;
	}
	if (pGameMessage)
	{
		pGameMessage->updateTip();   //弹窗里面的也要刷新显示
	}
	bool bShow = false;
	int iCount = GNS_PlayerMgr::GetInstance()->GetMailCount();
	if (iCount>0)
	{
		bShow = true;
	}
	const int ifullCount = 90;
	int iAllCount = GNS_PlayerMgr::GetInstance()->getAllMapListMailcount();
	m_MsgTips->setVisible(bShow);
	auto tex = static_cast<Text*>(m_MsgTips->getChildByName("Text_1"));
	if (tex)
	{
		if (iAllCount >= ifullCount)
		{
			tex->setString("满");
			tex->setVisible(true);
		}
		else
		{
			auto str = StringUtils::format("%02d", iCount);
			tex->setString(str);
			tex->setVisible((iCount > 0) ? true : false);
		}
	}
}

void GNS_HallScene::ShowFriendTips()
{
	if (m_FriendTips == nullptr)
	{
		return;
	}
	bool bShow = false;
	map<long long, CMD_InviteFriendInfo> *pMap = GNS_PlayerMgr::GetInstance()->getInviteFriend();
	int iAllCount = pMap->size();
	if (iAllCount>0)
	{
		bShow = true;
	}
	int iCount = pMap->size();
	m_FriendTips->setVisible(bShow);
	auto tex = static_cast<Text*>(m_FriendTips->getChildByName("Text_1_0"));
	if (tex)
	{
		auto str = StringUtils::format("%02d", iCount);
		tex->setString(str);
		tex->setVisible((iCount > 0) ? true : false);
	}

	if (pFriendLayer)
	{
		pFriendLayer->updateUnReadMailCount();
	}
}

void GNS_HallScene::GameBtnCallBack(cocos2d::Ref *pSender, ui::Widget::TouchEventType type)
{
	if (type == ui::Widget::TouchEventType::ENDED) {
		auto pButton = (Button *)pSender;
		int tag = pButton->getTag();
// 		if (pButton->getUserData()==NULL)
// 		{
// 			ShowCommonTips("敬请期待！");
// 		}
// 		else
		{
			startGameByTag(tag);
		}
		
	}
}

void GNS_HallScene::startGameByTag(int tag)
{
	CMD_SC_HALLGAME_LIST infoStruct = (*GNS_PlayerMgr::GetInstance()->getGameInfoStruct())[tag];
 	if (atoi(infoStruct.szVersionNO) == 0)
 		return;

	log("%s", infoStruct.szPacketName);
	log("%s", infoStruct.szVersionNO);
	string name = GNS_PlayerMgr::GetInstance()->getMyName();
	string passW = GNS_PlayerMgr::GetInstance()->getMyPassMD5();
	char PassWord[33] = { 0 };
	char PassWords[33] = { 0 };
#if (CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
	memcpy(PassWord, passW.c_str(), passW.length());
	memcpy(PassWords, SystemMgr::getInstance()->md5String(PassWord), 33);
	SystemMgr::getInstance()->setUserNameJNI(name.c_str(), passW.c_str(), 0);
#endif

	int Vaddress = 1;
	
#if (CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
	Vaddress = SystemMgr::getInstance()->getIsApkInstalled(infoStruct.szPacketName, infoStruct.szVersionNO);
	log("V = == %d", Vaddress);
	m_szDownAddr = infoStruct.szAndrDownAddr;
#endif
	if (Vaddress == 0) // 表示已经安装，且跟现在这个apk文件是一个版本
	{
#if (CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
		m_isStartGame = true;
		SystemMgr::getInstance()->startGameApp(infoStruct.szPacketName);
#endif
	}
	else
	{
		//Vaddress = 1 // 表示未安装
		//Vaddress = 2 // 表示已经安装，版本比现在这个版本要低，可以点击按钮更新
		if (m_PopWndDown == nullptr)
		{
			m_PopWndDown = GNS_YJFLayer::createLayer("MainScenes/AgreeTipLayer.csb");
			auto btnSubmit = (Button*)m_PopWndDown->m_RootNode->getChildByName("Button_1");
			btnSubmit->setTag(BTN_DOWN_SUBIMT);
			btnSubmit->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton,this));

			auto qx = (Button*)m_PopWndDown->m_RootNode->getChildByName("Button_2");
			qx->setTag(BTN_DOWN_QX);
			qx->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::menuitembutton, this));

			auto text = (Text*)m_PopWndDown->m_RootNode->getChildByName("Text_1");
			string str = StringUtils::format("发现新版本%s，是否下载？", infoStruct.szVersionNO);
			text->setString(str);
		}
		//m_PopWndDown->setManner(Vaddress, infoStruct.szAndrDownAddr);
		auto text = (Text*)m_PopWndDown->m_RootNode->getChildByName("Text_1");
		string str = StringUtils::format("发现新版本%s，是否下载？", infoStruct.szVersionNO);
		text->setString(str);
		m_PopWndDown->Show();
	}
}

void GNS_HallScene::ReqRankData(float delay)
{
	GNS_ClientHall::getInstance()->sendData(MAIN_MSG_PLAZA_GOLD_RANKING, SUB_CSG_GOLD_RANKING, 0, 0);	  //获取排行榜
}

void GNS_HallScene::delayShowSing(float delay)
{
	ShowSing();   //弹出公告
}


void GNS_HallScene::BtnAction(int tag)
{
	//先把 两个按钮屏蔽
	auto btnL = static_cast<Button*>(m_RootNode->getChildByName("Button_2"));
	btnL->setTouchEnabled(false);
	auto btnR = static_cast<Button*>(m_RootNode->getChildByName("Button_3"));
	btnR->setTouchEnabled(false);
	float offsetx = 0;
	float offsetDelayTime = 0.0f;
	float offsetScale = 0.2f;

	if (_mGameBtn.size() < 1)
		return;

	if (tag == BTN_RIGHT)
	{
		int Vsize = _mGameBtn.size();
		if (_mGameBtn[Vsize - 1]->isVisible() == true)
		{
			btnR->setEnabled(false);
			return;
		}
		btnL->setEnabled(true);

		if (m_showBtn[0] != nullptr && m_showBtn[1] != nullptr)
			offsetx = m_showBtn[0]->getPositionX() - m_showBtn[1]->getPositionX();
		else
			offsetx = _mGameBtn[0]->getPositionX() - _mGameBtn[1]->getPositionX();
		for (int i = _mGameBtn.size() - 1; i >=0; i--)
		{
			auto delay = DelayTime::create(offsetDelayTime*(2-i));
			auto moveB = MoveBy::create(m_actionTime, Point(offsetx, 0));
			auto act1 = CCEaseSineIn::create(moveB);
			auto callback1 = CallFuncN::create(this, callfuncN_selector(GNS_HallScene::BtnActionCallBack));
			auto seq1 = Sequence::create(delay, act1, callback1, nullptr);
			_mGameBtn[i]->runAction(seq1);
		}

		//更新m_showBtn
		if (m_showBtn.size() > 0)
		{
			auto btn1 = m_showBtn.front();
			auto btn2 = m_showBtn.back();
			if (btn1 != nullptr)
			{
				auto fo = FadeOut::create(m_actionTime);
				btn1->setVisible(false);
				btn1->runAction(fo);
			}
			m_showBtn.pop_front();
			int i = 0;
			for (; i < _mGameBtn.size(); i++)
			{
				if (btn2 != nullptr && _mGameBtn[i]->getTag() == btn2->getTag())
					break;
			}
			auto btn3 = _mGameBtn[i + 1];
			if (btn3 != nullptr)
			{
				auto fi = FadeIn::create(m_actionTime);
				btn3->setVisible(true);
				btn3->runAction(fi);
				m_showBtn.push_back(btn3);
				if (_mGameBtn[_mGameBtn.size() - 1]->isVisible())
					btnR->setEnabled(false);
			}
		}
	}
	else if (tag == BTN_LEFTT)
	{
		if (_mGameBtn[0]->isVisible() == true)
		{
			btnL->setEnabled(false);
			return;
		}
		btnR->setEnabled(true);

		if (m_showBtn[0] != nullptr && m_showBtn[1] != nullptr)
			offsetx = m_showBtn[1]->getPositionX() - m_showBtn[0]->getPositionX();
		else
			offsetx = _mGameBtn[1]->getPositionX() - _mGameBtn[0]->getPositionX();
		
		for (int i = 0; i < _mGameBtn.size(); i++)
		{
			auto delay = DelayTime::create(offsetDelayTime*i);
			auto moveB = MoveBy::create(m_actionTime, Point(offsetx, 0));
			auto act1 = CCEaseSineIn::create(moveB);
			auto callback1 = CallFuncN::create(this, callfuncN_selector(GNS_HallScene::BtnActionCallBack));
			auto seq1 = Sequence::create(delay, act1, callback1, nullptr);
			_mGameBtn[i]->runAction(seq1);
		}
		
		//更新m_showBtn
		if (m_showBtn.size() > 0)
		{
			auto btn1 = m_showBtn.back();
			auto btn2 = m_showBtn.front();
			if (btn1 != nullptr)
			{
				auto fo = FadeOut::create(m_actionTime);
				btn1->setVisible(false);
				btn1->runAction(fo);
			}
			m_showBtn.pop_back();
			int i = 0;
			for (; i < _mGameBtn.size(); i++)
			{
				if (btn2 != nullptr && _mGameBtn[i]->getTag() == btn2->getTag())
					break;
			}
			auto btn3 = _mGameBtn[i - 1];
			if (btn3 != nullptr)
			{
				auto fi = FadeIn::create(m_actionTime);
				btn3->setVisible(true);
				btn3->runAction(fi);
				m_showBtn.push_front(btn3);
				if (_mGameBtn[0]->isVisible())
					btnL->setEnabled(false);
			}
		}
	}
}

void GNS_HallScene::BtnActionCallBack(Node* sender)
{
	Button* btn = static_cast<Button*>(sender);
	if (btn->getPositionX()> 350 && btn->getPositionX()<450)
	{
		//btn->setScale(1);
	}
	else
	{
		//btn->setScale(0.5);
	}
}


void GNS_HallScene::selectBtnCallBack(float delay)
{
	auto btnL = static_cast<Button*>(m_RootNode->getChildByName("Button_2"));
	btnL->setTouchEnabled(true);
	auto btnR = static_cast<Button*>(m_RootNode->getChildByName("Button_3"));
	btnR->setTouchEnabled(true);
}



void GNS_HallScene::menuitembutton(cocos2d::Ref *pSender, ui::Widget::TouchEventType type){
    if (type==ui::Widget::TouchEventType::ENDED) {
        auto pButton = (Button *)pSender;
        int tag = pButton->getTag();
		GnsClientFrame* pGnsClientFrame = GnsClientFrame::getInstance();
		assert(pGnsClientFrame);
        switch (tag) {
		case BTN_LEFTT:
		{
			BtnAction(tag);
			scheduleOnce(schedule_selector(GNS_HallScene::selectBtnCallBack), m_actionTime);
			break;
		}
		case BTN_RIGHT:
		{
			BtnAction(tag);
			scheduleOnce(schedule_selector(GNS_HallScene::selectBtnCallBack), m_actionTime);
			break;
		}
		case BTN_DOWN_SUBIMT:
		{
			log("yyyyyyyyyyyyyy%s", m_szDownAddr.c_str());
#if (CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
			SystemMgr::getInstance()->runDownloadJNI(m_szDownAddr.c_str());
			log("jjjjjjjjjjj%s", m_szDownAddr.c_str());
#else

#endif
			m_PopWndDown->Show(false);//取消關閉自己
			break;
		}
		case BTN_DOWN_QX:
		{
			m_PopWndDown->Show(false);
			break;
		}
		case HALL_BACK:
            {
				setLoginOut();//退出
                break;
            }
            case HALL_INFO:		 //个人信息
            {
				ShowInfo();
                break;
            }
            case HALL_QR_TAG:	 // 二维码
            {
				ShowTwoCode(true);
                break;
            }
			case HALL_MSG:	   //消息
            {
				ShowMsg();
				break;
            }
            case HALL_FRIEND_TAG:	 //好友
            {
				ShowFriend();
                break;
            }
            case HALL_SYSTEM_TAG:	  //设置
            {
				ShowSetting();
                break;
            }
            case HALL_SIGN_TAG:		  //公告
            {
				ShowSing();
                break;
            }
            case HALL_LIST_TAG:	   //排行榜
            {
				CMD_CS_GetRanking data;
				data.nGameId = 1;
				data.nType = 1;
				pGnsClientFrame->sendMsg(HALLSERVER,MAIN_MSG_PLAZA_GOLD_RANKING, SUB_CSG_GOLD_RANKING, (char*)&data, sizeof(data));
				ShowConnectTips("获取数据中！");

				//5秒之后自动关闭
				this->scheduleOnce(schedule_selector(GNS_HallScene::closeConnectTips), 5);
				ShowRank();
                break;
            }
            case HALL_TICK_TAG:		  //兑奖
            {
				ShowTick();
                break;
            }
            case HALL_SERVICE:	  //客服
            {
				//获取官方联系方式   
				ShowServer();
				
                break;
            }
            default:
                break;
        }
    }
}

void GNS_HallScene::ShowSetting()
{
	if (pSystenLayer == nullptr)
	{
		pSystenLayer = GNS_SysTenLayer::createLayer();
		pSystenLayer->SetNodeName("MainScenes/SysTemLayer.csb");
	}
	pSystenLayer->Show(true);
}

void GNS_HallScene::ShowTick()
{
	if (pTickLayer == nullptr)
	{
		pTickLayer = GNS_TickLayer::createLayer();
		pTickLayer->SetNodeName("MainScenes/TickLayer.csb");
	}
	pTickLayer->Show(true);
}

void GNS_HallScene::setLoginOut()
{
	GNS_PlayerMgr::GetInstance()->resetAll();
	GnsClientFrame* pGnsClientFrame = GnsClientFrame::getInstance();
	assert(pGnsClientFrame);
	pGnsClientFrame->closeSocket(HALLSERVER);	  //断开dating服

	GNS_LoginScene::setIsRegistHallServer(false);

 	GNS_SceneMgr::getInstance()->replaceScene(SCENE_LOGIN);
}

void GNS_HallScene::ShowFriend()
{
	if (pFriendLayer==nullptr)
	{
		pFriendLayer = GNS_FriendLayer::createLayer();
		pFriendLayer->SetNodeName("MainScenes/FriendLayer.csb");
	}
	pFriendLayer->Show(true);
	pFriendLayer->setButtonState();
}

void GNS_HallScene::ShowRank()
{
	if (pRankLayer == nullptr)
	{
		pRankLayer = GNS_RankLayer::createLayer();
		pRankLayer->SetNodeName("MainScenes/rankList.csb");
	}
	pRankLayer->Show();
	//ankLayer->setButtonState();
}

void GNS_HallScene::ShowInfo()
{
	if (pSetMyInfo == nullptr)
	{
		pSetMyInfo = GNS_SetMyInfo::createLayer();
		pSetMyInfo->SetNodeName("MainScenes/MyInforLayer.csb");
	}
	pSetMyInfo->Show(true);
	pSetMyInfo->setButtonState();
}

void GNS_HallScene::ShowSing()
{
	if (pSingLayer == nullptr)
	{
		pSingLayer = GNS_SingLayer::createLayer();
		pSingLayer->SetNodeName("MainScenes/SingLayer.csb");
	}
	pSingLayer->updateNoticeText();
	pSingLayer->Show(true);
}

void GNS_HallScene::ShowServer()
{
	if (pServiceLayer == nullptr)
	{
		pServiceLayer = GNS_ServiceLayer::createLayer();
		pServiceLayer->SetNodeName("MainScenes/SeviceLayer.csb");
	}
	pServiceLayer->Show(true);
}

void GNS_HallScene::ShowMsg()
{
	 if (pGameMessage== nullptr)
	 {
		 pGameMessage = GNS_GameMessage::createLayer();
		 pGameMessage->SetNodeName("MainScenes/HallMsg.csb");
	 }
	 pGameMessage->Show(true);
	 pGameMessage->setButtonState();
}

void GNS_HallScene::ShowTwoCode(bool isShow)
{
	if (pQRLayer==nullptr)
	{
 		pQRLayer = GNS_QRLayer::createLayer();
 		pQRLayer->setQRsize(150.0f);
 		pQRLayer->SetNodeName("MainScenes/QRLayer.csb");
	}
	pQRLayer->Show(true);	
}

// 设置头像
void GNS_HallScene::setFaceLogo()
{
	auto pSprFaceLogo = static_cast<ImageView*>(m_RootNode->getChildByName("Image_3"));
	
	if (!pSprFaceLogo)
		return;

	auto pstrPath = StringUtils::format("face_%lld.png", GNS_PlayerMgr::GetInstance()->getMyLogoID());
	
	pSprFaceLogo->loadTexture(pstrPath.c_str());
}

void GNS_HallScene::setNickName(const std::string name)
{
	auto nameText = static_cast<Text*>(m_RootNode->getChildByName("Player_Name"));
	if (nameText)
	{
		nameText->setString(GTOU(name.c_str()));
	}
}

void GNS_HallScene::setExperienceGold(long long Chip)
{
	auto ChipText = static_cast<Text*>(m_RootNode->getChildByName("Text_3"));
	if (!ChipText)
		return;
	auto str = StringUtils::format("%ld", Chip);
	ChipText->setString(str.c_str());
}

void GNS_HallScene::setGameGold(long long gameGold)
{
	auto goldText = static_cast<Text*>(m_RootNode->getChildByName("Text_3_0"));
	if (!goldText)
		return;
	auto str = StringUtils::format("%lld", gameGold);
	goldText->setString(str.c_str());
}

// 事件桥梁定时器的回调函数
void GNS_HallScene::OnEventBridge(float dt)
{
	IEventBridge::EVENT_INFO eventInfo;

	while (IEventBridge::getInstance()->popFront(eventInfo))
	{
		GnsClientFrame* pGnsClientFrame = GnsClientFrame::getInstance();
		assert(pGnsClientFrame);

		int mainCode = eventInfo.iMainCode;
		switch (mainCode)
		{
		case CLIENT_INNER_CONNECT:					// 连接结果
		{
			int& iReconnectCount = (int&)eventInfo.szBody;
			connectResult(eventInfo.iClientId, eventInfo.iSubCode, iReconnectCount);
			break;
		}
		case CLIENT_INNER_RE_CONNECT:			// 断线重连
		{
			int& iReconnectCount = (int&)eventInfo.szBody;
			/*if (RECC_START_NO_CIRCLE == eventInfo.iSubCode)
			{
				ShowConnectTips("", false);
			}*/
			reConnectResult(eventInfo.iClientId, eventInfo.iSubCode, iReconnectCount);
			if (eventInfo.iSubCode == RECC_START_NO_CIRCLE)
			{
				ShowConnectTips("", false);
			}
			break;
		}
		case CLIENT_INNER_RE_CLOSE:		// 断线
		{
			// 断线时不需要作任何处理，断线的事项交由断线重连功能（CLIENT_INNER_RE_CONNECT）进行处理
			break;
		}

		default:
			break;
		}
		switch (eventInfo.iSubCode)
		{
		case SUB_SC_USER_KICKOUT:
		{
			// 主动断开	   帐号在其他地方登录了
			setLoginOut();
			GNS_PlayerMgr::GetInstance()->m_isKickout = true;
			break;
		}
		case SUB_SC_USER_KICKOUT_OVER_BURST:
		{
			setLoginOut();
			GNS_PlayerMgr::GetInstance()->m_isBaoji = true;
			break;
		}
		case SUB_SC_UPD_LOGIN_PWD_SUC: // 修改登陆密码成功
		{
			ShowCommonTips("密码修改成功，请重新登录！", true);
			break;
		}
		case SUB_SC_UPD_LOGIN_PWD_FAIL: // 修改登陆密码失败
		{
			CMD_UpdLoginPwdFail *pPwdFail = (CMD_UpdLoginPwdFail *)eventInfo.szBody;

			if (IDI_UPD_LOGIN_PWD_ERROR == pPwdFail->iRet)
			{
				ShowCommonTips("原密码错误", true);
				return;
			}
			ShowCommonTips("密码修改失败", true);
			break;
		}
		case SUB_CSG_UPD_NICKNAME: // 修改昵称
		{
			CMD_UpdNickNameRes *pUpdNickNameRes = (CMD_UpdNickNameRes *)eventInfo.szBody;
			if (!pUpdNickNameRes || sizeof(CMD_UpdNickNameRes) != eventInfo.iBodyLen)
			   return;
			if (0 == pUpdNickNameRes->iRet)
			{
			   GNS_PlayerMgr::GetInstance()->setMyNickName(pUpdNickNameRes->szNickName);
			   setNickName(GNS_PlayerMgr::GetInstance()->getMyNickName());
			}
			
			ShowCommonTips(GTOU(pUpdNickNameRes->szText));
			break;
		}
		case SUB_SC_UPD_CELLPHONE_FAIL: //手机号码修改失败
		{
			CMD_UpdCellPhoneFail  *pdat = (CMD_UpdCellPhoneFail*)eventInfo.szBody;
			ShowCommonTips(GTOU(pdat->szResText));
			break;
		}
		case SUB_SC_UPD_CELLPHONE_SUC:	 //手机号码修改成功
		{
			ShowCommonTips("修改成功");
			break;
		}
		case SUB_SC_UPD_SYSLOGOID_SUC: // 修改头像
		{
			setFaceLogo();
			break;
		}
		case SUB_CSG_SEL_USER_INFO: // 查询牌友
		{
			CMD_FriendData *pFriendData = (CMD_FriendData *)eventInfo.szBody;
			if (sizeof(CMD_FriendData) != eventInfo.iBodyLen || !pFriendData)
				return;
			GNS_PlayerMgr::GetInstance()->SetSearchFriendData(pFriendData);
			break;
		}
		case SUB_CSG_SEL_USER_INFO_FINISH: // 查询牌友完成
		{
			if (pFriendLayer)
			{
				pFriendLayer->ShowAddFriendList();
			}
			break;
		}
		case SUB_CSG_INVITE_FRIEND: // 好友邀请消息
		{
			CMD_InviteFriendInfo *pInviteFriend = (CMD_InviteFriendInfo *)eventInfo.szBody;
			if (!pInviteFriend || sizeof(CMD_InviteFriendInfo) != eventInfo.iBodyLen)
				return;

			//刷新tip
			ShowFriendTips();

			map<long long, CMD_InviteFriendInfo> *pMap = GNS_PlayerMgr::GetInstance()->getInviteFriend();
			if (pMap->end() != pMap->find(pInviteFriend->lInvitedUserId))
				break;

			pMap->insert(make_pair(pInviteFriend->lInvitedUserId, *pInviteFriend));
			if (pFriendLayer)
			{
				pFriendLayer->ShowReqFriendList();
			}
			
			//ShowFriendTips();
			break;
		}
		case SUB_SC_USER_FRIENDS: // 好友列表
		{
			CMD_FriendInfo *pFriendInfo = (CMD_FriendInfo *)eventInfo.szBody;
			if (!pFriendInfo || sizeof(CMD_FriendInfo) != eventInfo.iBodyLen)
				 return;
			map<long long, CMD_FriendInfo> *pMap = GNS_PlayerMgr::GetInstance()->getFriendList();
			if (pFriendInfo->lFriendUserId > 0)
			{   
					pMap->insert(make_pair(pFriendInfo->lFriendUserId, *pFriendInfo)); 
			}
			break;
		}
		case SUB_CS_DELETE_FRIEND_SUC:   //自己删除时接到服务端返回值
		{
			if (pFriendLayer)
			{
				pFriendLayer->showListViewByTag(BTN_F_LIST);
				pFriendLayer->showTipsOfdeleteFriend(false);
			}
			break;
		}
		case SUB_CS_DELETE_FRIEND: // 删除牌友
		{
			CMD_DeleteFriend *pDeleteFriend = (CMD_DeleteFriend *)eventInfo.szBody;
			if (!pDeleteFriend || sizeof(CMD_DeleteFriend) != eventInfo.iBodyLen)
			   return;
			map<long long, CMD_FriendInfo> *pMap = GNS_PlayerMgr::GetInstance()->getFriendList();
			if (pMap)
				pMap->erase(pDeleteFriend->lUserId);

			if (pFriendLayer)
			{
				pFriendLayer->showListViewByTag(BTN_F_LIST);
			}
			
			break;
		}
		case SUB_CSG_USER_SITE: // 更新牌友状态
		{
			CMD_UserSite *pUserSite = (CMD_UserSite *)eventInfo.szBody;
			if (!pUserSite || sizeof(CMD_UserSite) != eventInfo.iBodyLen)
				return;

			map<long long, CMD_FriendInfo> *pMap = GNS_PlayerMgr::GetInstance()->getFriendList();
			map<long long, CMD_FriendInfo>::iterator mIt = pMap->find(pUserSite->lUserId);
			if (pMap->end() != mIt)
			{
				memcpy(&mIt->second.stUserSite, pUserSite, sizeof(CMD_UserSite));
			}
			break;
		}
		case SUB_SC_NOTICE_MSG: // 广播消息
		{
			CMD_NoticeMsg *pNoticeMsg = (CMD_NoticeMsg *)eventInfo.szBody;
			if (!pNoticeMsg || eventInfo.iBodyLen != sizeof(CMD_NoticeMsg))
				break;
			break;
		}
		case SUB_SC_USER_LOGIN_GIVE:	// 登录赠送金币
		{
			CMD_SC_UserLoginGive *pUserLoginGive = (CMD_SC_UserLoginGive *)eventInfo.szBody;
			GNS_PlayerMgr::GetInstance()->setMyGameGold(GNS_PlayerMgr::GetInstance()->getMyGameGold() + pUserLoginGive->iGvieGold);
			GNS_PlayerMgr::GetInstance()->setMyExperienceGold(GNS_PlayerMgr::GetInstance()->getMyExperienceGold() + pUserLoginGive->iGiveExperiencegold);
			ShowCommonTips(GTOU(pUserLoginGive->szRetText), true);
			break;
		}
		case SUB_SC_ERROR_MSG:
		{	 
			CMD_Error_Msg *pError = (CMD_Error_Msg*)eventInfo.szBody;
			ShowCommonTips(GTOU(pError->_remark));
			break;
		}
		// 邮件
		case SUB_CS_MAIL:
		{
			CMD_Mail *pck = (CMD_Mail*)eventInfo.szBody;
			switch (pck->iType)
			{
				// 增加邮件
				case HAMDLE_MAIL_ADD:
				{
					GNS_PlayerMgr::GetInstance()->AddMailList(pck);
					if (pck->llUid == GNS_PlayerMgr::GetInstance()->getMyUserIdx())
					{
					}
					// 增加聊天内容
					long long llChatID = 0LL;
					// 增加聊天内容
					if (pGameMessage && pGameMessage->getFriendMsg() && pGameMessage->getFriendMsg()->isVisible())
					{
						llChatID = pGameMessage->getFriendMsg()->getSelectPlayerID();
						pGameMessage->getFriendMsg()->onShowFinished();

						// 自己发出去的邮件不提示，正在和发件人聊天不提示
						if (pck->llUid != GNS_PlayerMgr::GetInstance()->getMyUserIdx() && MAIL_FRIEND == pck->iMailType)
						{
							// 获取邮件列表中未读的邮件数量 
							CMD_Mail *pCMD_Mail = GNS_PlayerMgr::GetInstance()->FindMail(pck->llRid);
							if (pCMD_Mail)
							{
								CMD_Mail userMail(*pck);
								userMail.llRid = pck->llRid;
								userMail.llUid = GNS_PlayerMgr::GetInstance()->getMyUserIdx();
								userMail.iType = 2;
								pGnsClientFrame->sendMsg(0, MAIN_MSG_USER, SUB_CS_MAIL, (char*)&userMail, sizeof(userMail));

								pCMD_Mail->iReadReceipt = 1; // 本地设置为已读
								GNS_PlayerMgr::GetInstance()->UpdateMailToMapList(pCMD_Mail);
							}
						}
						
					}
					else
					{
						if (MAIL_FRIEND == pck->iMailType && pGameMessage!=nullptr)
						{
							pGameMessage->ShowPanle(MAIL_FRIEND);
						}
					}
					ShowMsgTips();
					break;
				}
					// 删除邮件
				case HAMDLE_MAIL_DEL:
				{
					// 失败
					if (pck->iError != 0)
						return;

					// 刷新UI
					if (pck->llRid > 0)
					{
						GNS_PlayerMgr::GetInstance()->DeleMailList(pck);

						
						if (pGameMessage)
						{
							if (pck->iMailType == 3)
							{
								pGameMessage->showFriendList();
							}
							else
							{
								pGameMessage->ShowGiftTemMsgList();
							}
							
						}
						//pGameMessage->getFriendMsg()->OnShowMsgViewByMailType(pck->iMailType);
						ShowMsgTips();
						
					}
					break;
				}
					// 查询/收到邮件(列表)
				case HAMDLE_MAIL_CHECK:
				{
					GNS_PlayerMgr::GetInstance()->AddMailList(pck);
					ShowMsgTips();
					break;
				}
				case HAMDLE_MAIL_ACCEPT_GOLD: //接受分享金币或充值 邮件
				{
					int i = 0;
					break;
				}
			}
			break;
		}
		case SUB_CS_MAIL_RECV_DONE:
		{
			ShowMsgTips();
			break;
		}
			// 分享金币
		case SUB_CSG_SHARE_GOLD:
		{
				CMD_ShareGold *pNewData = (CMD_ShareGold *)eventInfo.szBody;

				if (NULL == pNewData || eventInfo.iBodyLen != sizeof(CMD_ShareGold))
					return;

				if (0 == pNewData->iRet)
				{
					if (0 < pNewData->llGoldNumber)
					{
						if (pNewData->llFishFieldUserID == GNS_PlayerMgr::GetInstance()->getMyUserIdx()) // 分享人
						{
							GNS_PlayerMgr::GetInstance()->setMyGameGold(GNS_PlayerMgr::GetInstance()->getMyGameGold() - pNewData->llGoldNumber);
							setExperienceGold(GNS_PlayerMgr::GetInstance()->getMyExperienceGold());
							ShowCommonTips(GTOU(pNewData->szRet));
						}
						else if (pNewData->llWantShareUserID == GNS_PlayerMgr::GetInstance()->getMyUserIdx()) // 需要分享的玩家
						{
							GNS_PlayerMgr::GetInstance()->setMyGameGold(GNS_PlayerMgr::GetInstance()->getMyGameGold() + pNewData->llGoldNumber);
							setExperienceGold(GNS_PlayerMgr::GetInstance()->getMyGameGold());
						}
					}
				}
			break;
		}
		case SUB_SC_UPDATE_FRIEND_DATE://分享金币成功后，更新被分享好友的信息
		{
			CMD_FriendInfo *pFriendInfo = (CMD_FriendInfo *)eventInfo.szBody;
			if (!pFriendInfo || sizeof(CMD_FriendInfo) != eventInfo.iBodyLen)
			   return;

			if (pFriendInfo->lUserId == GNS_PlayerMgr::GetInstance()->getMyUserIdx())
			{
			   map<long long, CMD_FriendInfo> *pMap = GNS_PlayerMgr::GetInstance()->getFriendList();
			   if (NULL != pMap)
			   {
				   map<long long, CMD_FriendInfo>::iterator itr = pMap->find(pFriendInfo->lFriendUserId);
				   if (itr != pMap->end())
				   {
					   itr->second = *pFriendInfo;
				   }
			   }
			}
			break;
		}
		case SUB_SC_UPDATE_USER_INFO://更新玩家信息
		{
			CMD_Update_UserInfo *pUserInfo = (CMD_Update_UserInfo *)eventInfo.szBody;
			if (!pUserInfo || sizeof(CMD_Update_UserInfo) != eventInfo.iBodyLen)
				 return;
			if (pUserInfo->lUserID == GNS_PlayerMgr::GetInstance()->getMyUserIdx())
			{
				 GNS_PlayerMgr::GetInstance()->setMyExperienceGold(pUserInfo->lExperienceGold);
				 GNS_PlayerMgr::GetInstance()->setMyGameGold(pUserInfo->lGold);
				 setExperienceGold(GNS_PlayerMgr::GetInstance()->getMyExperienceGold());
				 setGameGold(GNS_PlayerMgr::GetInstance()->getMyGameGold());
			}
			break;
		}
		case SUB_SC_SHARE_GOLD_ERROR://分享金币 失败
		{
			 CMD_ShareGold *pNewData = (CMD_ShareGold*)eventInfo.szBody;
			 if (NULL == pNewData || eventInfo.iBodyLen != sizeof(CMD_ShareGold))
				 return;

			 if (0 != pNewData->iRet)
			 {
				 log("分享失败！===%s", pNewData->szRet);
				 if (pNewData->llFishFieldUserID == GNS_PlayerMgr::GetInstance()->getMyUserIdx()) // 分享人
				 {
					 ShowCommonTips(GTOU(pNewData->szRet), true);
				 }
			 }
			 break;
		}
		case SUB_SC_ACCEPT_ERROR: //领取错误,失败.
		{
			CMD_Mail *pNewData = (CMD_Mail*)eventInfo.szBody;
			if (NULL == pNewData || eventInfo.iBodyLen != sizeof(CMD_Mail))
			  return;

			if (0 != pNewData->iRet)
			{
			  log("分享失败！===%s", pNewData->szRet);
			  if (pNewData->llUid == GNS_PlayerMgr::GetInstance()->getMyUserIdx()) // 分享人
			  {
				  ShowCommonTips(GTOU(pNewData->szRet), true);
			  }
			}
			break;
		}
		case SUB_SC_SHARE_GOLD_RECEIVE_SEC:
		{
			 CMD_UpdateGold *pNewData = (CMD_UpdateGold*)eventInfo.szBody;
			 if (NULL == pNewData || eventInfo.iBodyLen != sizeof(CMD_UpdateGold))
				  return;

			 if (pNewData->llUserID == GNS_PlayerMgr::GetInstance()->getMyUserIdx()) // 分享人
			 {

				  GNS_PlayerMgr::GetInstance()->setMyGameGold(pNewData->llGold);
				  setGameGold(GNS_PlayerMgr::GetInstance()->getMyGameGold());
			 }
		}
		case SUB_CSG_GOLD_RANKING_FINISH: //// 获取金币排行完成
		{
			ShowConnectTips("",false);
			if (pRankLayer)
			{
				pRankLayer->ShowRankList(true);
			}
			break;
		}
		case  SUB_CSG_REQUEST_EXCHANGE_GOLD_TO_RMB_SUC:		 //兑奖成功
		{
			  CMD_CSG_ExchangeResult *pdata = (CMD_CSG_ExchangeResult*)eventInfo.szBody;
			  if (NULL == pdata || eventInfo.iBodyLen != sizeof(CMD_CSG_ExchangeResult))
				  return;
			  ShowCommonTips(GTOU(pdata->_mailText));
			  break;
		}
		case SUB_CSG_REQUEST_EXCHANGE_GOLD_TO_RMB_FAIL:		//兑奖失败
		{
				CMD_CSG_ExchangeFail  *pdata = (CMD_CSG_ExchangeFail *)eventInfo.szBody;
				if (NULL == pdata || eventInfo.iBodyLen != sizeof(CMD_CSG_ExchangeFail))
			    return;
				ShowCommonTips(GTOU(pdata->_remark));
			  break;
		}
		case SUB_SC_GAME_HALL_LIST_FINISH:
		{
			addGameBtn();
			break;
		}
			default:  
			{
				   break;
			}
		}

		if (m_isFinish)
			return;
	}
}

void GNS_HallScene::closeConnectTips(float dt)
{
	ShowConnectTips("", false);
}

void GNS_HallScene::addGameBtn()
{
	map<int, CMD_SC_HALLGAME_LIST> * gameMap = GNS_PlayerMgr::GetInstance()->getGameInfoStruct();
	if (gameMap->size() < 1)
		return;
	map<int, CMD_SC_HALLGAME_LIST>::iterator it = gameMap->begin();
	int count = 0;
	for (; it != gameMap->end(); ++it)
	{
		++m_gameCount;

		auto norName = StringUtils::format("GAME%d_1.png", it->second.nGameId);
		auto selName = StringUtils::format("GAME%d_2.png", it->second.nGameId);
		auto disName = StringUtils::format("GAME%d_3.png", it->second.nGameId);
		
		if (!FileUtils::getInstance()->isFileExist(norName))
			norName = "GAME1_1.png";
		if (!FileUtils::getInstance()->isFileExist(selName))
			selName = "GAME1_2.png";
		if (!FileUtils::getInstance()->isFileExist(disName))
			disName = "GAME1_3.png";

		Button * testBtn = Button::create(norName, selName, disName);
		testBtn->setSize(Size(220, 310));
		testBtn->setTag(it->second.nGameId);
		testBtn->addTouchEventListener(CC_CALLBACK_2(GNS_HallScene::GameBtnCallBack, this));
		if (it->second.bIsForbidRun == 0)
			testBtn->setEnabled(false);
		else if (it->second.bIsForbidRun == 1)
			testBtn->setEnabled(true);
		if (count > 2)
			testBtn->setVisible(false);
		else
		{
			testBtn->setVisible(true);
			if (atoi(it->second.szVersionNO) != 0)
				m_showBtn.push_back(testBtn);
		}
		if (atoi(it->second.szVersionNO) != 0)
		{
			++count;
			testBtn->setPosition(Vec2(winsize.width * 0.25 * count, winsize.height * 0.5));
			m_RootNode->addChild(testBtn, 10000);
			_mGameBtn.push_back(testBtn);
		}
	}

	auto game0 = static_cast<Button*>(m_RootNode->getChildByName("Button_9"));
	auto game1 = static_cast<Button*>(m_RootNode->getChildByName("Button_10"));
	auto game2 = static_cast<Button*>(m_RootNode->getChildByName("Button_11"));
	game0->setVisible(false);
	game1->setVisible(false);
	game2->setVisible(false);

	auto btnR = static_cast<Button*>(m_RootNode->getChildByName("Button_3"));
	btnR->setEnabled(true);
	auto btnL = static_cast<Button*>(m_RootNode->getChildByName("Button_2"));
	btnL->setEnabled(true);
}

void GNS_HallScene::showGame(float dt)
{
	if (GNS_PlayerMgr::GetInstance()->getGetAllGame())
	{
		this->unschedule(schedule_selector(GNS_HallScene::showGame));
		addGameBtn();
	}
}
